package com.ftg.learn.util;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ftg.learn.vo.UserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 通用service封装，用来完成对于sql语句的通用化封装处理
 *
 * @author kangjx
 * @date 2022/10/27
 */
@Service
public class ServiceUtil {

    @Resource
    MapperUtil mapperUtil;

    /**
     * 通用sql语句封装
     *
     * @param sql   语句
     * @param page  页码
     * @param limit 显示条目
     * @return ResultJson 显示数据为map
     */
    public ResultJson pageUtilForMap(String sql, int page, int limit) {
        IPage<Map<String, Object>> iPage = new Page(page, limit);
        iPage.setRecords(mapperUtil.pageUtil((page - 1) * limit, limit, sql));
        iPage.setTotal(mapperUtil.countUtil(sql));
        return ResultJson.OK(iPage);
    }

    /**
     * 通用sql语句封装
     *
     * @param sql   语句
     * @param page  页码
     * @param limit 显示条目
     * @return ResultJson 显示数据为T  即vo
     */
    public ResultJson pageUtilForT(String sql, int page, int limit, Class c) {
        List<Object> json = new ArrayList<>();
        try {
            List<Map<String, Object>> list = mapperUtil.pageUtil((page - 1) * limit, limit, sql);

            for (int j = 0; j < list.size(); j++) {
                Object temp = c.newInstance();
                Field[] fs = c.getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    PropertyDescriptor pd = new PropertyDescriptor(fs[i].getName(), c);
                    Method ms = pd.getWriteMethod();
                    TableField an = fs[i].getAnnotation(TableField.class);
                    if (list.get(j).containsKey(fs[i].getName())) {
                        ms.invoke(temp, list.get(j).get(fs[i].getName()));
                    } else if (an != null && list.get(j).containsKey(an.value())) {
                        ms.invoke(temp, list.get(j).get(an.value()));
                    }
                }
                json.add(temp);
            }

        } catch (InstantiationException | IllegalAccessException | IntrospectionException | InvocationTargetException e) {
            e.printStackTrace();
        }

        IPage<Object> iPage = new Page<>(page, limit);
        iPage.setRecords(json);
        iPage.setTotal(mapperUtil.countUtil(sql));
        return ResultJson.OK(iPage);
    }

}
